<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>

<!--<script type="text/javascript">-->
<!--    window.onload = function () {-->
<!--        document.getElementById("usr").innerText = localStorage.getItem("loginName")-->
<!--    }-->
<!--</script>-->
<style>
    .el-dropdown-link {
        cursor: pointer;
        color: white;
    }

    .el-icon-arrow-down {
        font-size: 12px;
    }

</style>
<body>

<div id="app" v-loading="loading">

    <div style="text-align: center">
        <el-menu

                :default-active="activeIndex2"
                class="el-menu-demo"
                mode="horizontal"
                @select="handleSelect"
                background-color="#545c64"
                text-color="#fff"
                active-text-color="#ffd04b">
            <el-menu-item index="1" @click="updateIframe('index2')">首页</el-menu-item>
            <el-menu-item index="12" @click="updateIframe('add')">添加页面</el-menu-item>
            <el-menu-item index="2" @click="updateIframe('delete')">删除页面</el-menu-item>
            <el-menu-item index="3" @click="updateIframe('find')">查询页面</el-menu-item>

            <el-menu-item index="4" @click="updateIframe('update')">修改页面</el-menu-item>
            <el-menu-item index="5" @click="updateIframe('userList')">用户列表</el-menu-item>
            <el-menu-item index="6" @click="updateIframe('userLog')">登录日志</el-menu-item>
            <el-menu-item index="7" @click="updateIframe('operationLog')">操作日志</el-menu-item>
            <el-menu-item index="11" @click="updateIframe('img')">图片管理</el-menu-item>
            <el-menu-item index="13" @click="dialogVisible3 ='true'">添加用户</el-menu-item>
            <el-menu-item index="8" @click="updateIframe('userInfo')">
                <strong>登录用户:</strong>
                <el-tag type="success" color="white" v-html="loginName"></el-tag>
                <!--                登录用户:<span id="usr"></span>-->
            </el-menu-item>
            <el-menu-item index="10" @click="updateIframe('updatePass')">修改密码</el-menu-item>
            <el-menu-item index="9" >
                <el-link @click="logout" type="primary" :underline="false">注销</el-link>
            </el-menu-item>

            <el-menu-item index="13" v-show="loginName=='admin'">
                <el-badge class="item">
                    <el-button @click="dialogVisible = true" size="mini">发布通知</el-button>
                </el-badge>
            </el-menu-item>

            <el-menu-item index="13" v-show="loginName!='admin'">
                <el-badge :value="messageList.length==0?'':'new'" class="item">
                    <el-button @click="opendialogVisible2" size="mini">收到信息</el-button>
                </el-badge>
            </el-menu-item>
        </el-menu>

    </div>
    <iframe height="700px" width="100%" :src="goSrc"></iframe>
    <!--    fullscreen-->

    <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="50%"
            center
            :before-close="handleClose">

        <div style="text-align: center">
            <div>
                <el-tag type="info">在线人数:{{onlineNum}}</el-tag>
            </div>

            <div style="text-align: center;padding-top: 20px">
                <el-checkbox v-model="checked2">发送所有人</el-checkbox>
            </div>

            <div style="padding-top: 20px">
                <el-checkbox-group v-model="checkList" :disabled="isButton">
                    <el-checkbox v-for="user in messageBean.onlineUsers" v-show="user!='admin'"
                                 :label="user"></el-checkbox>
                </el-checkbox-group>
            </div>

            <div style="padding-top: 20px">
                <el-input
                        type="textarea"
                        :rows="5"
                        placeholder="请输入内容"
                        maxlength="500"
                        show-word-limit
                        v-model="messages.message">
                </el-input>
                <el-button type="success" @click="sendMessage">发送消息</el-button>
            </div>
        </div>
    </el-dialog>

    <el-dialog
            title="提示"
            :visible.sync="dialogVisible2"
            width="50%"
            center
            :before-close="handleClose2">

        <div style="text-align: center">
            <div>
                <el-alert v-for="message in readMessage"
                          :title="'来自管理员admin:'+message"
                          type="info">
                </el-alert>
            </div>

        </div>

    </el-dialog>

    <el-dialog
            title="添加用户"
            :visible.sync="dialogVisible3"
            width="50%"
            center
            :before-close="handleClose3">

        <div>
            <el-input
                    size="medium"
                    placeholder="请输入用户名"
                    v-model="addName"
                    maxlength="10"
                    show-word-limit
                    clearable>
            </el-input>

            <h4 style="text-align: center">权限列表</h4>
            <el-checkbox-group v-model="checkedPermissions">
                <el-checkbox v-for="permission in permissionList" :label="permission.id" :key="permission.id"><span
                        v-html="permission.permissionName"></span></el-checkbox>
            </el-checkbox-group>
        </div>
        <div style="text-align: center;padding-top: 30px">
            <el-button type="primary" @click="addUser">添加</el-button>
        </div>

    </el-dialog>
</div>
<script th:src="@{/axios.min.js}"></script>
<script th:src="@{/vue.js}"></script>

<!-- 引入样式 -->
<link rel="stylesheet" th:href="@{/element-ui.css}">
<!-- 引入组件库 -->
<script th:src="@{/element-ui.js}"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            activeIndex: '1',
            activeIndex2: '1',
            goSrc: "/index2",
            loginName: "",
            loading: false,
            dialogVisible: false,   //发送消息弹窗
            dialogVisible2: false,  //接收消息弹窗
            dialogVisible3: false,  //添加用户弹窗
            messageBean: {
                onlineUsers: "",
                messageType: null
            },
            //在线人数
            onlineNum: 0,
            messages: {
                message: "", //发送信息的内容
                userId: "",
                to: "",
                isAll: 2  //不是发给全部人
            },
            permissionList: [],   //权限列表
            checkedPermissions: [],  //选中的权限
            checkList: [],    //发送消息的对象
            messageList: [],   //接收的消息
            websockets: null,   //连接
            readMessage: [],     //读过的消息
            checked2: false,    //是否发送所有人
            isButton: false,    //是否选择选中框
            addName: "",  //添加的用户名

        },
        watch: {
            // 此处监听checked2变量，当期有变化时执行
            // item1为新值，item2为旧值
            checked2(item1, item2) {
                if (item1) {
                    this.messages.isAll = 1
                    this.isButton = true
                } else {
                    this.messages.isAll = 2
                    this.isButton = false
                }
                immediate:true // watch侦听操作内的函数会立刻被执行
            }
        },
        created() {
            this.findPermission()
            this.loginName = localStorage.getItem("loginName")
            //var websocket= null
            let that = this
            //判断当前浏览器是否支持WebSocket
            if ('WebSocket' in window) {
                //连接WebSocket节点 140.143.201.125
                this.websockets = new WebSocket("ws://localhost:8085/connectWebSocket/" + this.loginName);
            } else {
                alert('Not support websocket')
            }


            //连接发生错误的回调方法
            this.websockets.onerror = function () {
                setMessageInnerHTML("error");
            };


            //连接成功建立的回调方法
            this.websockets.onopen = function (event) {

            }


            //接收到消息的回调方法
            this.websockets.onmessage = function (event) {
                if (JSON.parse(event.data).messageType == 4) {
                    //把接收到的消息存到集合中
                    if (that.dialogVisible2 == true) {
                        //that.readMessage=localStorage.getItem("messageList")
                        that.readMessage.push((JSON.parse(event.data)).textMessage)

                        localStorage.setItem("messageList", that.readMessage)
                    } else {
                        that.messageList.push((JSON.parse(event.data)).textMessage)
                    }

                }

                that.messageBean = JSON.parse(event.data)
                that.onlineNum = that.messageBean.onlineUsers.length;
            }


            //连接关闭的回调方法
            this.websockets.onclose = function () {

            }


            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                localStorage.removeItem("messageList")
                this.websockets.close();
            }


            //将消息显示在网页上
            function setMessageInnerHTML(innerHTML) {
                //document.getElementById('message').innerHTML += innerHTML + '<br/>';
            }


            //关闭连接
            function closeWebSocket() {
                this.websockets.close();
            }

            //发送消息
            function send() {
                //websocket.send(message);
            }
        },
        methods: {
            //添加用户
            addUser() {
                if (this.addName == '' || this.addName == null) {
                    this.$message.error("请输入用户名");
                    return false;
                }

                if (this.addName.length < 6) {
                    this.$message.error("用户名6位到10位");
                    return false;
                }

                if (this.checkedPermissions == null || this.checkedPermissions.length == 0) {
                    this.$message.error("请至少选择一个权限");
                    return false;
                }
                axios.post("/user/add/" + this.addName + "/" + this.checkedPermissions).then(resp => {
                    if (resp.data.flag) {
                        this.$message({
                            message: resp.data.message,
                            type: 'success'
                        });
                    } else {
                        this.$message.error(resp.data.message);
                    }
                    this.dialogVisible3=false
                    this.addName=""
                    this.checkedPermissions=[]
                })
            },

            //管理员发送消息
            sendMessage() {
                if (this.messages.isAll == 2 && this.checkList.length == 0) {
                    this.$message({
                        message: '请选择发送对象!',
                        type: 'warning'
                    });
                    return false;
                }

                if (this.messages.message == '' || this.messages.message == null) {
                    this.$message({
                        message: '发送内容不能为空!',
                        type: 'warning'
                    });
                    return false;
                }

                //是否发送全部人
                if (this.checked2) {
                    this.messages.isAll = 1
                } else {
                    this.messages.isAll = 2
                }

                let to = JSON.stringify(this.checkList)
                this.messages.to = this.checkList
                this.messages.userId = "admin"
                this.websockets.send(JSON.stringify(this.messages))

                this.messages.message = ""
                this.$message({
                    message: '发送成功!',
                    type: 'success'
                });
            },

            logout() {
                this.loading = true

                localStorage.removeItem("loginName")
                axios.get("/user/logout").then(resp => {
                    if (resp.data.flag) {
                        this.loading = false
                        this.$message({
                            message: resp.data.message,
                            type: 'success'
                        });

                        setTimeout(function () {
                            window.location.href = "/login"
                        }, 1000)
                    } else {
                        this.loading = false
                        this.$message.error(resp.data.message);
                    }
                })
            },

            //查询权限列表
            findPermission() {
                axios.get("/permission/findPermission").then(resp => {
                    if (resp.data.flag) {
                        this.permissionList = resp.data.data
                    } else {
                        this.$message.error(resp.data.message);
                    }
                    this.loading = false
                })
            },

            //打开接收消息
            opendialogVisible2() {
                this.readMessage = localStorage.getItem("messageList")
                if (this.readMessage != null && this.readMessage.length > 0) {
                    this.readMessage = this.readMessage.split(",")
                    if (this.messageList != null && this.messageList.length > 0) {
                        this.readMessage.push(this.messageList)
                        this.messageList = []
                        localStorage.setItem("messageList", this.readMessage)
                    }

                } else {
                    if (this.messageList != null && this.messageList.length > 0) {
                        this.readMessage = this.messageList
                        this.messageList = []
                        localStorage.setItem("messageList", this.readMessage)
                    }
                }

                this.dialogVisible2 = true
            },

            //关闭接收消息
            handleClose2() {
                this.dialogVisible2 = false
                if (this.messageList != null && this.messageList.length > 0) {
                    this.readMessage.push(this.messageList)
                    localStorage.setItem("messageList", this.readMessage)
                    //清空接收到的消息
                    this.messageList = []
                }

            },

            updateIframe(id) {
                this.goSrc = id
            },
            handleSelect(key, keyPath) {

            }
        }
    })
</script>
</body>


</html>